import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:shop/config/config.dart';
import 'package:shop/http/HttpUtil.dart';
import 'package:shop/route/my_route.dart';
import 'package:shop/shop/life/RefundType.dart';

import '../OrderListPage.dart';
import '../PayMima.dart';
import 'OrderDetail.dart';

class AllOfOrder extends StatefulWidget {
  List list;
  AllOfOrder(this.list);
  @override
  _AllOfOrder createState() => _AllOfOrder();
}

class _AllOfOrder extends State<AllOfOrder>
{
   List orderList=[];
   String userId;//用户ID
   // 分页当前页
   int page=1;
   // 上拉加载控制器
   RefreshController _refreshController = RefreshController(initialRefresh: false);
   _AllOfOrder(){
     _onLoading();
   }
   // 刷新时调用
   void _onRefresh() async{
     // monitor network fetch
     //await Future.delayed(Duration(milliseconds: 1000));
     // _onLoading();
     // if failed,use refreshFailed()
     _refreshController.refreshCompleted();
   }
   // 加载数据的函数
   void _onLoading() async{
     // 获取内存存储的用户id
     SharedPreferences prefs = await SharedPreferences.getInstance();
     userId = prefs.getString("userId");
     // monitor network fetch
     // await Future.delayed(Duration(milliseconds: 1000));
     // Response response = await Dio().get("http://xllm.szghrj.com:8082/app/order/searchUserOrder?limit=10&orPeisongType=1&orStatus=10&page=${page}&userId=${userId}");
     // var x = json.decode(response.toString());
     // var x = await HttpUtil().get("/app/order/searchUserOrder?limit=10&orPeisongType=1&orStatus=10&page=${page}&userId=${userId}");
     var x = await HttpUtil().get("/waimai/mOder/searchUserMOrder?limit=10&orPeisongType=1&orStatus=10&page=${page}&userId=${userId}");
     page++;
     if(x['code']==200){
       orderList.addAll(x['data']);
     }
     if(x['data'].length<1){
       _refreshController.loadNoData();
       return;
     }
     // if failed,use loadFailed(),if no data return,use LoadNodata()
     if(mounted){
       setState(() {});
       _refreshController.loadComplete();
     }
   }
   // 显示订单支付按钮/收货按钮
   Widget showOrderBtn(obj){
     String s="";
     switch(obj['orStatus']){
       case 0:s="立即支付";break;
       // case 2:s="立即收货";break;
       // case 1:s="申请退款";break;
     }
     return s=="" ? null: Center(child:Text(s,style: TextStyle(color: Colors.white),));
   }
   // 显示删除订单按钮
   Widget showDeleteOrder(obj){
     String s="";
     switch(obj['orStatus']){
       case 0:s="删除订单";break;
     }
     return s=="" ? null: Center(child:Text(s,style: TextStyle(color: Colors.white),));
   }
   // 显示订单状态
    Widget showOrderStatus(obj){
      String s="待付款";
      switch(obj['orStatus']){
        case 0:s="待付款";break;
        case 1:s="商家已接单";break;
        case 2:s="商家出餐完成";break;
        case 3:s="骑手已取货，配送中";break;
        case 4:s="已送达，待评价";break;
        case 5:s="已评价";break;
        case 6:s="退换货申请中";break;
        case 7:s="退换货完成";break;
        case 8:s="退款完成";break;
        case 9:s="取消订单";break;
        // case 1:s="待发货";break;
        // case 2:s="待收货";break;
        // case 3:s="已完成";break;
        // case 4:s="退换货中";break;
        // case 5:s="退货完成";break;
        // case 6:s="退款成功";break;
      }
      return Text(s,style: TextStyle(color: Colors.red),);
    }
    // 显示订单
   GestureDetector _showOrders(item,i) {
     // 解析订单详情
     var orderDetail =(item['morderDetailList']) ;
      return GestureDetector(
        child: Container( // 一个订单信息
          // margin: EdgeInsets.fromLTRB(10, 10, 10, 40 ),
          width: ScreenUtil().setWidth(464),
          height: ScreenUtil().setHeight(100),
          decoration: BoxDecoration(color: Colors.white,borderRadius: BorderRadius.all(Radius.circular(10))),
          child:SingleChildScrollView(
            child:
          Column(
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  // Text("官方旗舰店"),
                  Text(item['merchant']['mname']),
                  showOrderStatus(item),
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  CachedNetworkImage(imageUrl: Config.getInstance().getHost()+orderDetail[0]['mgoods']['gimages'],width:ScreenUtil().setWidth(70),height: ScreenUtil().setHeight(70),),
                  Column(
                    children: [
                    Container(width:ScreenUtil().setWidth(290),height:ScreenUtil().setHeight(25),child: Text("${orderDetail[0]['mgoods']['gname']}"),),
                    Container(width:ScreenUtil().setWidth(290),height:ScreenUtil().setHeight(55),child: Text("${orderDetail[0]['mgoods']['jianjie']}",style: TextStyle(color: Colors.black12),))
                  ],),
                  Column(children: [
                    Container(child: Text("￥${orderDetail[0]['odCost']}"),),
                    Container(child: Text("*${orderDetail[0]['odNum']}"),),
                  ],)
                ],
              ),
              Divider(),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Container(child: Text("共${item['orTotalnum']}件"),),
                  Container(child: Row(children: [
                    // Container(child: Text("总价:￥${item['orPrice']}",style: TextStyle(color: Colors.black12),),),
                    Container(child: Text("实付:￥${item['orPrice']}"),),
                  ],)),

                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  GestureDetector(child: Container(
                    width: 80,
                    child: showDeleteOrder(item),
                    decoration: BoxDecoration(
                      color: Colors.deepOrange,
                      borderRadius: BorderRadius.all(Radius.circular(20.0)),
                    ),
                  ),onTap: () async {
                    print("删除订单");
                    showDialog<Null>(
                      context: context,
                      barrierDismissible: false,
                      builder: (BuildContext context) {
                        return new AlertDialog(
                          title: new Text('删除订单'),
                          content: Text('确认删除订单?'),
                          actions: <Widget>[
                            new FlatButton(
                              child: new Text('取消'),
                              onPressed: (){
                                Navigator.of(context).pop();
                              },
                            ),
                            new FlatButton(
                              child: new Text('确定'),
                              onPressed: () async{
                                // var x = await HttpUtil().get("/app/order/deleteOrder?orId=${item['orId']}");
                                var x = await HttpUtil().get("/waimai/mOder/deleteMOrder?orId=${item['id']}");
                                if(x['code']==200){
                                  setState(() {
                                    orderList.removeWhere((element) {
                                      return element==orderList[i];
                                    });
                                  });
                                  Fluttertoast.showToast(
                                      msg: "订单取消成功",
                                      toastLength: Toast.LENGTH_SHORT,
                                      gravity: ToastGravity.BOTTOM,
                                      timeInSecForIosWeb: 1,
                                      backgroundColor: Colors.black45,
                                      textColor: Colors.white,
                                      fontSize: 16.0
                                  );
                                }else{
                                  Fluttertoast.showToast(
                                      msg: "取消失败",
                                      toastLength: Toast.LENGTH_SHORT,
                                      gravity: ToastGravity.BOTTOM,
                                      timeInSecForIosWeb: 1,
                                      backgroundColor: Colors.black45,
                                      textColor: Colors.white,
                                      fontSize: 16.0
                                  );
                                }
                                Navigator.of(context).pop();
                              },
                            ),
                          ],
                        );
                      },
                    ).then((val) {
                      print(val);
                    });
                  },),
                  SizedBox(width: 10,),
                  GestureDetector(child: Container(
                      width:80,
                      // padding: EdgeInsets.fromLTRB(0, 5, 0, 5),
                      child: showOrderBtn(item),
                      decoration: BoxDecoration(
                        color: Colors.deepOrange,
                        borderRadius: BorderRadius.all(Radius.circular(20.0)),
                      )
                  ),onTap: () async {
                    int orStatus = item['orStatus'];
                    if(orStatus==0){
                      String unionid = item['unionid'];
                      //判断商家是否营业中
                      var x = await HttpUtil().get("/waimai/mOrderPay/panduanMerchantonLine?ddhao="+unionid);
                      if(x['code']==200){
                        double allMoney = item['orPrice'];
                        var value = await MyRoute.push(PayMima(unionid: unionid,userId: userId,money: allMoney,type: 4));
                        if(value=='1'){
                          setState(() {
                            orderList.removeWhere((element) {
                              return element==orderList[i];
                            });
                          });
                        }
                      }else{
                        Fluttertoast.showToast(
                            msg: x['msg']
                        );
                      }
                    }else if(orStatus==2){
                      showDialog<Null>(
                        context: context,
                        barrierDismissible: false,
                        builder: (BuildContext context) {
                          return new AlertDialog(
                            title: new Text('收货'),
                            content: Text('确认收货?'),
                            actions: <Widget>[
                              new FlatButton(
                                child: new Text('取消'),
                                onPressed: (){
                                  Navigator.of(context).pop();
                                },
                              ),
                              new FlatButton(
                                child: new Text('确定'),
                                onPressed: () async{
                                  Navigator.of(context).pop();
                                  String orId = item['orId'];
                                  // var y = await HttpUtil().get("/app/order/confirmShouhuo?orId="+orId);
                                  var y = await HttpUtil().get("/waimai/mOder/confirmShouhuo?orId="+orId);
                                  if(y['code']==200){
                                    Fluttertoast.showToast(
                                        msg: "收货成功"
                                    );
                                    Future.delayed(Duration(seconds: 2), (){
                                      //跳全部订单页面
                                      MyRoute.replace(OrderListPage(showIndex:'0'));
                                    });
                                  }
                                  setState(() {});
                                },
                              ),
                            ],
                          );
                        },
                      ).then((val) {
                        print(val);
                      });
                    }else if(orStatus==1){
                      var value = await MyRoute.push(RefundType(odid: item['odId'],orid: item['orId'],gid: item['gid'],orStatus: '1',));
                      if(value==1){
                        setState(() {
                          orderList.removeWhere((element) {
                            return element==orderList[i];
                          });
                        });
                      }
                    }
                  },)
                  ]
              )
            ],
          ),
          )
        ),
        onTap: (){
          MyRoute.push(OrderDetail(orid:item['id'],orStatus: item['orStatus'].toString()));
          // Navigator.push(
          //     context,
          //     MaterialPageRoute(
          //       builder:(context)=>OrderDetail(orid:item['id'],orStatus: item['orStatus'].toString()),
          //     )
          // );
        },
      );
   }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: SmartRefresher(
          enablePullDown: false,
          enablePullUp: true,
          header: WaterDropHeader(),
          footer: CustomFooter(
            builder: (BuildContext context,LoadStatus mode){
              Widget body ;
              if(mode==LoadStatus.idle){
                body =  Text("上拉加载");
              }
              else if(mode==LoadStatus.loading){
                body =  CupertinoActivityIndicator();
              }
              else if(mode == LoadStatus.failed){
                body = Text("加载失败！点击重试！");
              }
              else if(mode == LoadStatus.canLoading){
                body = Text("松手,加载更多!");
              }
              else{
                body = Text("没有更多数据了!");
              }
              return Container(
                height: 55.0,
                child: Center(child:body),
              );
            },
          ),
          controller: _refreshController,
          onRefresh: _onRefresh,
          onLoading: _onLoading,
          child: ListView.builder(
            itemBuilder: (c, i) => Card(child: _showOrders(orderList[i],i)),
            itemExtent: 170.0,    // 每个的高度
            itemCount: orderList.length,
          ),
        ),
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
